import json, base64
from food.models import Food
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage

@csrf_exempt
def calendar_add(request):
    if request.method == "POST":
        rep = json.loads(request.body)
        try:
            date = rep['date']
            noon = rep['noon']
            night = rep['night']
        except:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '缺少参数'})
        data = {'date': date}
        if noon:
            tmp_noon = {}
            for item in noon:
                tmp_noon[item] = {'score': 0, 'cover': ''}
            data['noon'] = tmp_noon
        else:
            data['noon'] = {}

        if night:
            tmp_night = {}
            for item in night:
                tmp_night[item] = {'score': 0, 'cover': ''}
            data['night'] = tmp_night
        else:
            data['night'] = {}
        # if not noon and not night:
        #     return JsonResponse({'code': -1, 'status': 'error', 'msg': '至少填写一顿饭'})
        try:
            if Food.objects.filter(date=date).exists():
                Food.objects.filter(date=date).update(**data)
            else:
                Food.objects.create(**data).save()
            return JsonResponse({'code': 0, 'status': 'success', 'msg': '添加成功'})
        except Exception as e:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': str(e)})

@csrf_exempt
def calendar_data(request):
    if request.method == "POST":
        rep = json.loads(request.body)
        try:
            start_time = rep['start_time']
            last_time = rep['last_time']
        except:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '缺少参数'})
        md = Food.objects.filter(date__range=[start_time, last_time])
        if md.count() > 0:
            data = {}
            for item in md:
                if item.noon: tmp_noon = ",".join([k for k,v in item.noon.items()])
                else: tmp_noon = ""
                if item.night: tmp_night = ",".join([k for k,v in item.night.items()])
                else: tmp_night = ""
                data[item.date.strftime("%Y-%m-%d")] = {'noon': tmp_noon, 'night': tmp_night}
        else: data = []
        return JsonResponse({'code': 0, 'status': 'success', 'msg': '查询成功', 'data': data})


@csrf_exempt
def score_data(request):
    if request.method == "POST":
        rep = json.loads(request.body)
        try:
            pageSize = int(rep['pageSize'])
            currentPage = int(rep['currentPage'])
        except:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '缺少参数'})

        md = Food.objects.all()
        pd = Paginator(md, pageSize)

        if pd.count == 0:
            return JsonResponse({'code': 0, 'status': 'success', 'msg': '查询成功', 'total': 0, 'data': {}})
        elif pd.count < currentPage:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '请选择正确的页码'})
        try:
            context = pd.page(currentPage)
        except EmptyPage:
            context = pd.page((pd.count()//pageSize) + 1)
        data = {}
        for item in context:
            tmp_noon,tmp_night = {}, {}
            if item.noon: tmp_noon = item.noon
            if item.night: tmp_night = item.night
            data[item.date.strftime("%Y-%m-%d")] = {'noon': tmp_noon, 'night': tmp_night}
        return JsonResponse({'code': 0, 'status': 'success', 'msg': '查询成功', 'total': md.count(), 'data': data})

@csrf_exempt
def score_upd_cover(request):
    if request.method == "POST":
        file = request.FILES.get('file')
        date = request.POST.get('date')
        time = request.POST.get('time')
        food = request.POST.get('food')

        if not file or not date or not time or not food:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '请填写完整的参数'})

        base64img = f"data:image/jpg;base64,{base64.b64encode(file.read()).decode('utf-8')}"

        try:
            tmp_food = Food.objects.get(date=date)
            if time == 'noon':
                tmp_noon = tmp_food.noon
                tmp_noon[food]['cover'] = base64img
                tmp_food.noon = tmp_noon
            if time == 'night':
                tmp_night = tmp_food.night
                tmp_night[food]['cover'] = base64img
                tmp_food.night = tmp_night
            tmp_food.save()
            return JsonResponse({'code': 0, 'status': 'error', 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': str(e)})

@csrf_exempt
def score_upd_score(request):
    if request.method == "POST":
        rep = json.loads(request.body)
        try:
            date = rep['date']
            time = rep['time']
            food = rep['food']
            score = rep['score']
        except:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '参数错误'})

        try:
            tmp_food = Food.objects.get(date=date)
            if time == 'noon':
                tmp_noon = tmp_food.noon
                tmp_noon[food]['score'] = score
                tmp_food.noon = tmp_noon
            if time == 'night':
                tmp_night = tmp_food.night
                tmp_night[food]['score'] = score
                tmp_food.night = tmp_night
            tmp_food.save()
            return JsonResponse({'code': 0, 'status': 'error', 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': str(e)})

@csrf_exempt
def score_del_cover(request):
    if request.method == "POST":
        rep = json.loads(request.body)
        try:
            date = rep['date']
            time = rep['time']
            food = rep['food']
        except:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': '参数错误'})

        try:
            tmp_food = Food.objects.get(date=date)
            if time == 'noon':
                tmp_noon = tmp_food.noon
                tmp_noon[food]['cover'] = ""
                tmp_food.noon = tmp_noon
            if time == 'night':
                tmp_night = tmp_food.night
                tmp_night[food]['cover'] = ""
                tmp_food.night = tmp_night
            tmp_food.save()
            return JsonResponse({'code': 0, 'status': 'error', 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': -1, 'status': 'error', 'msg': str(e)})